package com.mjfeed.activity;

import java.util.ArrayList;
import java.util.List;

import com.mjfeed.adapter.AreaSpinnerAdapter;
import com.mjfeed.bean.AreaJSON;
import com.mjfeed.bean.ReceiverJSON;
import com.mjfeed.service.AreaService;
import com.mjfeed.service.ReceiverService;
import com.mjfeed.util.NetUtils;
import com.mjfeed.util.SPUtils;
import com.mjfeed.widget.LoadingDialog;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 收货地址详情 用于添加和编辑
 * @author zhaominglei
 * @date 2014-12-17
 * 
 */
public class ReceiverDetailActivity extends Activity implements OnClickListener {
	@SuppressWarnings("unused")
	private static final String TAG = ReceiverDetailActivity.class.getSimpleName();
	private AreaService areaService = new AreaService();
	private ReceiverService receiverService = new ReceiverService();
	
	private ImageView goHome;
	private TextView detailTitle;
	private EditText consigneeEdt; //收货人
	//地区下拉列表
	private Spinner provinceSpinner;
	private AreaSpinnerAdapter provinceAdapter;
	private List<AreaJSON> provinceAreas = new ArrayList<AreaJSON>();
	private Spinner citySpinner;
	private AreaSpinnerAdapter cityAdapter;
	private List<AreaJSON> cityAreas = new ArrayList<AreaJSON>();
	private Spinner countySpinner;
	private AreaSpinnerAdapter countyAdapter;
	private List<AreaJSON> countyAreas = new ArrayList<AreaJSON>();
	private EditText addressEdt; //地址
	private EditText zipCodeEdt; //邮编
	private EditText phoneEdt; //电话
	private CheckBox isDefaultBox; //是否默认
	private Button saveBtn; //保存
	private LoadingDialog loadingDialog; //加载框
	private String referer; //来自那个链接
	private String action; //动作
	private ReceiverJSON receiverJSON; //收货地址
	private String username; //用户名
	private String sign; //签名
	private ReceiverJSON receiver; //收货地址
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_receiver_detail);
		
		init();
	}

	private void init() {
		goHome = (ImageView) findViewById(R.id.receiver_detail_gohome);
		detailTitle = (TextView) findViewById(R.id.receiver_detail_title);
		consigneeEdt = (EditText) findViewById(R.id.receiver_detail_consignee_edt);
		provinceSpinner = (Spinner) findViewById(R.id.province_spinner);
		citySpinner = (Spinner) findViewById(R.id.city_spinner);
		countySpinner = (Spinner) findViewById(R.id.county_spinner);
		addressEdt = (EditText) findViewById(R.id.receiver_detail_address_edt);
		zipCodeEdt = (EditText) findViewById(R.id.receiver_detail_zipCode_edt);
		phoneEdt = (EditText) findViewById(R.id.receiver_detail_phone_edt);
		isDefaultBox = (CheckBox) findViewById(R.id.receiver_detail_isDefault);
		saveBtn = (Button) findViewById(R.id.receiver_detail_save);
		
		goHome.setOnClickListener(this);
		loadingDialog = new LoadingDialog(this);
		provinceAreas = areaService.getProvince(this);
		provinceAdapter = new AreaSpinnerAdapter(this, provinceAreas);
		provinceSpinner.setAdapter(provinceAdapter);
		cityAdapter = new AreaSpinnerAdapter(this, cityAreas);
		citySpinner.setAdapter(cityAdapter);
		countyAdapter = new AreaSpinnerAdapter(this, countyAreas);
		countySpinner.setAdapter(countyAdapter);
		provinceSpinner.setOnItemSelectedListener(new ProvinceSelectedListener());
		citySpinner.setOnItemSelectedListener(new CitySelectedListener());
		saveBtn.setOnClickListener(this);
		
		referer = getIntent().getStringExtra("referer");
		username = (String)SPUtils.get(getApplicationContext(), "username", "");
		sign = (String)SPUtils.get(getApplicationContext(), "sign", "");
		action = getIntent().getStringExtra("action");
		//添加
		if (action != null && action.equals("add")) {
			detailTitle.setText(R.string.receiver_detail_title_add);
		}
		//编辑
		if (action != null && action.equals("edit")) {
			detailTitle.setText(R.string.receiver_detail_title_edit);
			receiverJSON = (ReceiverJSON)getIntent().getSerializableExtra("receiverJSON");
			if (receiverJSON != null) {
				consigneeEdt.setText(receiverJSON.getConsignee());
				consigneeEdt.setTag(receiverJSON.getReceiverId());
				AreaJSON areaJSON = areaService.getById(this, receiverJSON.getAreaId());
				String[] treePath = areaJSON.getTreePath().split(",");
				if (treePath.length == 2) {
					int firstIndex = 0;
					for (int i = 0; i < provinceAreas.size(); i++) {
						if(areaJSON.getParentId() == provinceAreas.get(i).getAreaId()) {
							firstIndex = i;
							break;
						}
					}
					provinceSpinner.setSelection(firstIndex, true);
					cityAreas = areaService.getCity(this, areaJSON.getParentId());
					cityAdapter.setAreas(cityAreas);
					cityAdapter.notifyDataSetChanged();
					int secondIndex = 0;
					for (int i = 0; i < cityAreas.size(); i++) {
						if(areaJSON.getAreaId() == cityAreas.get(i).getAreaId()) {
							secondIndex = i;
							break;
						}
					}
					citySpinner.setSelection(secondIndex, true);
				} else {
					long firstAreaId = 0l,secondAreaId = 0l;
					for (int i = 0; (treePath != null && treePath.length > 0) && i < treePath.length; i++) {
						if (i == 1) {
							firstAreaId = Long.valueOf(treePath[i]);
						}
						if (i == 2) {
							secondAreaId = Long.valueOf(treePath[i]);
						}
					}
					int firstIndex = 0;
					for (int i = 0; i < provinceAreas.size(); i++) {
						if(firstAreaId == provinceAreas.get(i).getAreaId()) {
							firstIndex = i;
							break;
						}
					}
					provinceSpinner.setSelection(firstIndex, true);
					cityAreas = areaService.getCity(this, firstAreaId);
					cityAdapter.setAreas(cityAreas);
					cityAdapter.notifyDataSetChanged();
					int secondIndex = 0;
					for (int i = 0; i < cityAreas.size(); i++) {
						if(secondAreaId == cityAreas.get(i).getAreaId()) {
							secondIndex = i;
							break;
						}
					}
					citySpinner.setSelection(secondIndex, true);
					countyAreas = areaService.getCounty(this, secondAreaId);
					countyAdapter.setAreas(countyAreas);
					countyAdapter.notifyDataSetChanged();
					int threeIndex = 0;
					for (int i = 0; i < countyAreas.size(); i++) {
						if(areaJSON.getAreaId().equals(countyAreas.get(i).getAreaId())) {
							threeIndex = i;
							break;
						}
					}
					countySpinner.setSelection(threeIndex, true);
				}
				addressEdt.setText(receiverJSON.getAddress());
				zipCodeEdt.setText(receiverJSON.getZipCode());
				phoneEdt.setText(receiverJSON.getPhone());
				if (receiverJSON.getIsDefault()) {
					isDefaultBox.setChecked(true);
				} else {
					isDefaultBox.setChecked(false);
				}
			}
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.receiver_detail_gohome:
			Intent intent = new Intent(getApplicationContext(), ReceiverListActivity.class);
			intent.putExtra("referer", "ReceiverDetailActivity");
			startActivity(intent);
			finish();
			break;
		case R.id.receiver_detail_save:
			save(v);
			break;
			
		default:
			break;
		}
	}

	/**
	 * 保存
	 */
	private void save(View v) {
		String consignee = consigneeEdt.getText().toString();
		String address = addressEdt.getText().toString();
		String zipCode = zipCodeEdt.getText().toString();
		String phone = phoneEdt.getText().toString();
		boolean isDefault = isDefaultBox.isChecked();
		
		if (consignee == null || consignee.equals("")) {
			Toast.makeText(v.getContext(), R.string.receiver_detail_check_error1, Toast.LENGTH_SHORT).show();
			return;
		}
		if (address == null || address.equals("")) {
			Toast.makeText(v.getContext(), R.string.receiver_detail_check_error2, Toast.LENGTH_SHORT).show();
			return;
		}
		if (zipCode == null || zipCode.equals("")) {
			Toast.makeText(v.getContext(), R.string.receiver_detail_check_error3, Toast.LENGTH_SHORT).show();
			return;
		}
		if (phone == null || phone.equals("")) {
			Toast.makeText(v.getContext(), R.string.receiver_detail_check_error4, Toast.LENGTH_SHORT).show();
			return;
		}
		receiver = new ReceiverJSON();
		receiver.setAddress(address);
		receiver.setConsignee(consignee);
		receiver.setIsDefault(isDefault);
		receiver.setPhone(phone);
		receiver.setZipCode(zipCode);
		if (action != null && action.equals("edit")) { //编辑
			Long receiverId = (Long)consigneeEdt.getTag();
			receiver.setReceiverId(receiverId);
		}
		AreaJSON cityArea = (AreaJSON)citySpinner.getSelectedItem();
		Long cityAreaId = cityArea.getAreaId();
		Long areaId = cityAreaId;
		AreaJSON countyArea = (AreaJSON)countySpinner.getSelectedItem();
		if (countyArea != null) {
			Long countyAreaId = countyArea.getAreaId();
			if (countyAreaId != null && countyAreaId.longValue() > 0l) {
				areaId = countyAreaId;
			}
		}
		receiver.setAreaId(areaId);
		if (NetUtils.isConnected(getApplicationContext())) {
			loadingDialog.show();
			new ReceiverSaveAsyncTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 省选择监听器
	 */
	public class ProvinceSelectedListener implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			Long areaId = (Long)view.getTag();
			if (areaId != null && areaId > 0) {
				cityAreas = areaService.getCity(parent.getContext(), areaId);
				cityAdapter.setAreas(cityAreas);
				cityAdapter.notifyDataSetChanged();
				
				AreaJSON firstCity = cityAreas.get(0);
				countyAreas = areaService.getCounty(parent.getContext(), firstCity.getAreaId());
				countyAdapter.setAreas(countyAreas);
				countyAdapter.notifyDataSetChanged();
			}
		}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	}
	
	/**
	 * 市选择监听器
	 */
	public class CitySelectedListener implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			Long areaId = (Long)view.getTag();
			if (areaId != null && areaId > 0) {
				countyAreas = areaService.getCounty(parent.getContext(), areaId);
				countyAdapter.setAreas(countyAreas);
				countyAdapter.notifyDataSetChanged();
			} 
		}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	}
	
	
	public class ReceiverSaveAsyncTask extends AsyncTask<String, String, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			return receiverService.saveReceiver(receiver, referer, username, sign);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			loadingDialog.dismiss();
			if (result) {
				Toast.makeText(getApplicationContext(), R.string.save_success, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), R.string.save_error, Toast.LENGTH_SHORT).show();
			}
			Intent intent = new Intent(getApplicationContext(), ReceiverListActivity.class);
			intent.putExtra("referer", "ReceiverDetailActivity");
			startActivity(intent);
			finish();
		}
		
	}
}
